package com.yami.shop.admin.controller;

import cn.hutool.core.io.FileUtil;
import com.yami.shop.dao.AttachFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Locale;

@Controller
public class ResourceController {

    @Value("${app.uploadPath}")
    public String filepath;




    @GetMapping("/static/**")
    public ResponseEntity<InputStreamResource> file(HttpServletRequest request) throws IOException {
        String servletPath = request.getServletPath();
        String filename = servletPath.substring(8);

        HttpHeaders headers =  new HttpHeaders();
        String contentType = "application/octet-stream";
        String extName = FileUtil.extName(filename);
        String[] imgType = new String[]{"png","gif","bmp","jpg","jpeg"};
        if(Arrays.asList(imgType).contains(extName.toLowerCase(Locale.ROOT))){
            contentType = "image/"+extName;
            headers.set("Cache-Control","max-age=36000");
        }

        FileSystemResource file = new FileSystemResource(filepath+'/'+filename);

        if(file.exists()){
            return ResponseEntity.ok().headers(headers).contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(new InputStreamResource(file.getInputStream()));
        }else{
            return ResponseEntity.notFound().build();
        }


    }
}
